package com.cx.mall.scheduler.controller;

import com.cx.mall.common.util.ResponseVo;
import com.cx.mall.scheduler.service.IBuyService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seckill/buy")
public class BuyController {
    @Autowired
    private IBuyService buyService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    @GetMapping("/dcount/{aid}/{sid}")
    public ResponseVo dcount(@PathVariable("aid") Integer activityId, @PathVariable("sid") String skuId) {


        String lockName = "seckill:lock:sku:" + activityId + skuId;

        RLock lock = redissonClient.getLock(lockName);

        try {
            boolean result = lock.tryLock(10, 10, TimeUnit.SECONDS);
            if (result) {
                buyService.dcount(activityId,skuId);
            }else {
                lock.unlock();
                return ResponseVo.fail("已售罄");
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e+"获取锁失败");
        }
        return ResponseVo.success();
    }
}